package fafmessenger.control;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import fafmessenger.entity.Contact;
import fafmessenger.entity.Message;

//http://www.screaming-penguin.com/node/7742


public class DataController{
	
	private static final String DATABASE_NAME = "FAFMessenger.db";
	private static final int DATABASE_VERSION = 1;
	private static final String TABLE_NAME = "Message";
	
	private Context context;
	private SQLiteDatabase db;
	private ArrayList<fafmessenger.entity.Message> messages;
	private ArrayList<Contact> contacts;
	
	public DataController(Context context){
		this.context = context;
		OpenHelper openHelper = new OpenHelper(this.context);
		this.db = openHelper.getWritableDatabase();
		messages = new ArrayList<fafmessenger.entity.Message>();
		contacts = new ArrayList<Contact>();
	}
 
	public void deleteAll(){
		this.db.delete(TABLE_NAME, null, null);
		messages.clear();
		contacts.clear();
	}
	
	public void saveConversations(fafmessenger.entity.Message message)
	{
		String temp = "INSERT INTO " + TABLE_NAME + " (`timestamp`, `body`, `from`, `to`) " +
		"VALUES ('" + message.getTimestamp() + "', '" + message.getBody() + "', '" + message.getFrom() + "', '" + message.getTo() + "');";
		this.db.execSQL("INSERT INTO " + TABLE_NAME + " (`timestamp`, `body`, `from`, `to`) " +
						"VALUES ('" + message.getTimestamp() + "', '" + message.getBody() + "', '" + message.getFrom() + "', '" + message.getTo() + "');");
	}
	
	public ArrayList<fafmessenger.entity.Message> getMessages() {
		return messages;
	}

	public ArrayList<Contact> getContacts() {
		return contacts;
	}

	//Berichten ophalen uit de storage v/d telefoon
	public ArrayList<fafmessenger.entity.Message> getAllConversations()
	{
		messages.clear();
		contacts.clear();
		try {
		ArrayList<fafmessenger.entity.Message> messages = new ArrayList<Message>();
		Cursor cursor = this.db.query(TABLE_NAME, new String[]{"id", "`timestamp`", "body", "`from`", "`to`"}, null, null, null, null, null);
		
	      if (cursor.moveToFirst() != false) {
	    	  do {
	    		  java.sql.Timestamp ts1 = java.sql.Timestamp.valueOf(cursor.getString(1));		
	    		  fafmessenger.entity.Message newMessage = new Message(cursor.getInt(0), ts1 ,cursor.getString(2),cursor.getString(3),cursor.getString(4));
	    		  
	    		  messages.add(newMessage);
	    	     } 
	    	  while (cursor.moveToNext());
	    	 	 }
	      
	      if (cursor != null && !cursor.isClosed()) {
	    	  cursor.close();
	          }
		
	      	return messages;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	//Controleer of contact bestaat
	public boolean checkContactExistence(Message m){
		boolean contactExists;
		contactExists = false;
		
		if (contacts.size() == 0){}
		
		else{
			for (Contact c : contacts){
				if (c.getMobilenumber().equalsIgnoreCase(m.getFrom())){
					contactExists = true;
				}
			}
		}
		return contactExists;
	}
	
	//Messages aan de contacten koppelen
	public ArrayList<Contact> getContactsWithConversations(){
		messages = getAllConversations();
		for (fafmessenger.entity.Message m : messages){
			if (checkContactExistence(m) == false){
				contacts.add(new Contact("", m.getFrom()));
			}
			
			//Message aan de bijbehorende contact koppelen
			for(Contact c : contacts){
				if (c.getMobilenumber().equalsIgnoreCase(m.getFrom())){
						c.getMessages().add(m);
				}
			}
		}
		return contacts;	
	}
	
	//Contact zoeken op naam
	public Contact getContactByNickname(String nickname) {
		Contact returnvalue = null;
		for (Contact c : contacts) {
			if (c.getNickname().equalsIgnoreCase(nickname)) {
				returnvalue = c;
				break;
			}
		}
		return returnvalue;
	}
	
	//Contact zoeken op nummer
	public Contact getContactByMobilenumber(String mobilenumber) {
		getContactsWithConversations();
		
		Contact returnvalue = null;
		for (Contact c : contacts) {
			if (c.getMobilenumber().equalsIgnoreCase(mobilenumber)) {
				returnvalue = c;
				break;
			}
		}
		return returnvalue;
	}
	
	public void deleteConversation(String mobilenumber) {
		this.db.execSQL("DELETE FROM `"+TABLE_NAME+"` WHERE `from` = '"+mobilenumber+"';");
	}
	
	public void closeDb(){
		this.db.close();
	}
	
	public void openDb(){
		OpenHelper openHelper = new OpenHelper(this.context);
		this.db = openHelper.getWritableDatabase();
	}
	
	
	//de OpenHelper
	private static class OpenHelper extends SQLiteOpenHelper {

			      OpenHelper(Context context) {
			         super(context, DATABASE_NAME, null, DATABASE_VERSION);
			      }
			 
			      @Override
			      public void onCreate(SQLiteDatabase db) {
			    	  
			         db.execSQL("CREATE TABLE "+TABLE_NAME+"(id INTEGER AUTO INCREMENT PRIMARY KEY, `timestamp` DATETIME, body TEXT, `from` VARCHAR(32), `to` VARCHAR(32))");
			    	  }
			 
			      @Override
			      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
			         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			         onCreate(db);
			      }
		}
}
